package summerbug.hanzi.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import summerbug.hanzi.MyApplication;
import summerbug.hanzi.api.ApiManager;
import summerbug.hanzi.model.HanZiTable;
import summerbug.hanzi.model.Poem;
import summerbug.hanzi.model.XinHuaZiDian;
import summerbug.hanzi.model.dao.DaoSession;
import summerbug.hanzi.model.dao.HanZiTableDao;

/**
 * Created by 76336 on 2018/5/13.
 */

public class NetworkService extends Service {

    StringBuffer imgUrl = new StringBuffer();
    StringBuffer poem_html = new StringBuffer();
    List<Poem> poems = new ArrayList<>();
    int flag = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("tag","onStartCommand:"+intent.getExtras().getString("zd"));
        final String word = intent.getExtras().getString("zd");

        Observable.create(new Observable.OnSubscribe<List<HanZiTable>>() {
            @Override
            public void call(Subscriber<? super List<HanZiTable>> subscriber) {
                try {
                    Document doc = Jsoup.connect("https://www.gushiwen.org/").get();
                    Elements all = doc.select("div.cont");
                    //0-3-6  3n-3
                    poem_html.append(all.select("p").select("a").get(0).attr("abs:href"));
                    Document doc_poem = Jsoup.connect(poem_html.toString()).get();
                    Elements all_poem = doc_poem.select("div.left");
                    if (all_poem.select("p.source").select("a").get(1).text()!="佚名") {
                        poem_html.delete(0, poem_html.length());
                        poem_html.append(all_poem.select("p.source").select("a").get(1).attr("abs:href"));
                    }
                    Document doc_author = Jsoup.connect(poem_html.toString()).get();
                    Elements all_author = doc_author.select("div.sonspic").select("div.cont");

                    Log.d("tag","作者信息:"+all_author.text());
                    Log.d("tag", "标题:"+all_poem.select("h1").text());
                    Log.d("tag", "朝代:"+all_poem.select("p.source").select("a").get(0).text());
                    Log.d("tag", "作者: "+all_poem.select("p.source").select("a").get(1).text());
                    Log.d("tag","内容:"+all_poem.select("div.contson").get(0).text());
                    Log.d("tag", "翻译: "+all_poem.select("div.contyishang").select("p").get(0).text());
                    poem_html.delete(0,poem_html.length());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .subscribe();

        Observable.create(new Observable.OnSubscribe<XinHuaZiDian>() {
            @Override
            public void call(Subscriber<? super XinHuaZiDian> subscriber) {
                try {
                    //还是一样先从一个URL加载一个Document对象。
                    Document doc = Jsoup.connect("https://hanyu.baidu.com/s?wd=屌&device=pc&from=home").get();
                    //字顺动画div所在位置
                    Elements pic = doc.select("div.alter-text");
                    //打印出字顺动画.gif的地址
                    imgUrl.append(pic.get(0).select("img").attr("data-gif"));
                    Log.d("tag", "call: "+imgUrl);
                    getZiDian(word);
                }catch(Exception e) {
                    Log.i("mytag", e.toString());
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .subscribe();

        return super.onStartCommand(intent, flags, startId);

    }

    private void getZiDian(String word) {
        ApiManager.getZiDianData("89205d2ef2f061cfd5a884827a9ebeae", "屌")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Observer<XinHuaZiDian> mObserver = new Observer<XinHuaZiDian>() {
        @Override
        public void onCompleted() {
            Log.d("tag", "onCompleted: ");
        }

        @Override
        public void onError(Throwable e) {
            Log.d("tag", "onError: "+e.getMessage());
        }

        @Override
        public void onNext(XinHuaZiDian xinHuaZiDian) {
            XinHuaZiDian.ResultBean resultBean = xinHuaZiDian.getResult();
            DaoSession daoSession = MyApplication.getInstance().getDaoSession();

            Intent intent = new Intent("ACTION_REFRESH_UI");
            HanZiTableDao hzDao = daoSession.getHanZiTableDao();
            HanZiTable hzTable = new HanZiTable();
            hzTable.setZi(resultBean.getZi());
            hzTable.setPy(resultBean.getPy());
            hzTable.setPinyin(resultBean.getPinyin());
            hzTable.setBihua(resultBean.getBihua());
            hzTable.setBushou(resultBean.getBushou());
            hzTable.setJianjie(resultBean.getJijie());
            hzTable.setWubi(resultBean.getWubi());
            hzTable.setChecked(false);

            if (imgUrl.toString()!="") {
                hzTable.setImgurl(imgUrl.toString());
                imgUrl.delete(0,imgUrl.length());
            }
            hzDao.insert(hzTable);
            Log.d("tag", "onNext: "+hzTable.getBihua());

            sendBroadcast(intent);
        }
    };
}
